<script setup lang="ts">
import { deleteMenu, editMenu, getMenuList, updateOrAddMenu } from '@/api/menus';
import type { CreateOrEditMenuData, MenuData } from '@/api/menus';
import { useToggle } from '@vueuse/core/index.cjs';
import type { FormInstance, FormRules } from 'element-plus';
import { useI18n } from 'vue-i18n';

// 国际化
const { t } = useI18n();

// Vueuse加载效果
const [isLoading, toggleLoading] = useToggle(false);

// 弹窗
const [dialogVisible, toggleDialogVisible] = useToggle(false);

const dialogType = ref<0 | 1>(0); // 0新增 1编辑

// 菜单列表初始化
const menuList = ref<MenuData[]>([]);

// 获取菜单列表
async function fetchData() {
    toggleLoading(true)
    const { data } = await getMenuList();
    if (data.code === '000000') {
        menuList.value = data.data;
    } else {
        ElMessage.error(t('menuList.fetchError'));
        throw new Error(t('menuList.fetchError'));
    }
    toggleLoading(false);
}

// 一级菜单遍历
const topMenu = computed(() => menuList.value.filter(menu => menu.level === 1))


// 编辑框表单初始化
const initialForm = {
    name: '',
    icon: '',
    href: '',
    parentId: -1,
    description: '',
    orderNum: 0,
    shown: false
}

const form = ref<CreateOrEditMenuData>({ ...initialForm });

// 添加逻辑
function hdlAdd() {
    // 添加标识为0
    dialogType.value = 0;
    // 每次打开都初始化输入框
    form.value = { ...initialForm };
    toggleDialogVisible(true);
}

// 删除逻辑
async function hdlDelete(id: string) {
    await ElMessageBox.confirm('确认删除该菜单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(() => {
        ElMessage.info('取消删除');
        return new Promise(() => { }); // pending状态
    })
    toggleLoading(true);

    // 调用接口函数
    const { data } = await deleteMenu(id);
    if (data.code === '000000') {
        ElMessage.success('菜单删除成功');
        fetchData();
    } else {
        ElMessage.error('菜单删除失败');
        throw new Error('菜单删除失败');
    }
    toggleLoading(false);
}


// 编辑逻辑
const editId = ref('');

async function hdlEdit(value: MenuData) {
    const { id, ...data } = value
    editId.value = id.toString();
    form.value = { ...data };
    dialogType.value = 1;
    toggleDialogVisible(true);
}


// 表单提交逻辑
async function hdlSubmit() {
    if (!formRef.value) {
        console.error('formRef is not initialized');
        return;
    }
    // 表单校验
    await formRef.value.validate();
    toggleLoading(true);
    if (dialogType.value === 0) {
        // 新增
        const { data } = await updateOrAddMenu(form.value);
        if (data.code === '000000') {
            ElMessage.success('菜单添加成功')
            fetchData();
        } else {
            ElMessage.error('菜单添加失败')
            throw new Error('菜单添加失败');
        }
        toggleDialogVisible(false);
    } else {
        // 编辑
        const { data } = await editMenu(editId.value);
        if (data.code === '000000') {
            form.value = data.data.menuInfo
            ElMessage.success('菜单编辑成功')
            fetchData();
        } else {
            ElMessage.error('菜单编辑失败')
            throw new Error('菜单编辑失败');
        }
        toggleDialogVisible(false);
    }
    toggleLoading(false);
}

// 挂载渲染列表
onMounted(fetchData);


// 表单校验
const formRef = useTemplateRef<FormInstance>("formEl");

const rules = reactive<FormRules<typeof initialForm>>({
    name: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, message: '长度至少2个字符', trigger: 'blur' }
    ],
    icon: [
        { required: true, message: '请输入菜单图标', trigger: 'blur' },
        { min: 2, message: '长度至少2个字符', trigger: 'blur' }
    ],
    href: [
        { required: true, message: '请输入菜单路径', trigger: 'blur' },
        { min: 2, message: '长度至少2个字符', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入菜单描述', trigger: 'blur' },
        { min: 2, message: '长度至少2个字符', trigger: 'blur' }
    ],
    orderNum: [
        { required: true, message: '请输入菜单排序', trigger: 'blur' },
        { type: 'number', message: '请输入正确的排序', trigger: 'blur' }
    ]
})  
</script>

<template>
    <div class="menu-index">
        <el-dialog v-model="dialogVisible" width="700" :title="dialogType === 0 ? '新增菜单' : '编辑菜单'">
            <el-form ref="formEl" :rules="rules" :model="form" :label-width="100">
                <el-form-item label="菜单名称" prop="name">
                    <ElInput v-model="form.name" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="菜单图标" prop="icon">
                    <ElInput v-model="form.icon" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="菜单路径" prop="href">
                    <ElInput v-model="form.href" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="上级菜单">
                    <ElSelect v-model="form.parentId" style="width: 500px;">
                        <ElOption label="顶层菜单" :value="-1" />
                        <ElOption v-for="menu in topMenu" :key="menu.id" :label="menu.name" :value="menu.id" />
                    </ElSelect>
                </el-form-item>
                <el-form-item label="菜单描述" prop="description">
                    <ElInput v-model="form.description" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="图标名称" prop="icon">
                    <ElInput v-model="form.icon" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="是否显示">
                    <ElSwitch v-model:model-value="form.shown" :active-value=true :inactive-value=false />
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <ElInput v-model="form.orderNum" style="width: 500px;" />
                </el-form-item>
            </el-form>
            <template #footer>
                <ElButton @click="toggleDialogVisible(false)" :loading="isLoading">取消</ElButton>
                <ElButton @click="hdlSubmit" :loading="isLoading">确定</ElButton>
            </template>
        </el-dialog>
        <div>
            <ElButton type="primary" size="large" @click="hdlAdd" :disabled="isLoading">{{ t('menuList.addButton') }}
            </ElButton>
        </div>
        <el-divider>
            <el-icon><el-icon-star-filled /></el-icon>
        </el-divider>
        <div v-loading="isLoading">
            <ElTable :data="menuList" border style="width: 100%">
                <ElTableColumn type="index" label="编号" align="center" />
                <ElTableColumn prop="name" label="菜单名称" align="center" />
                <ElTableColumn prop="level" label="菜单层级" align="center" />
                <ElTableColumn prop="icon" label="菜单图标" align="center" />
                <ElTableColumn prop="orderNum" label="菜单排序" align="center" />
                <ElTableColumn label="操作" align="center">
                    <template #default="scope">
                        <ElButton @click="hdlEdit(scope.row)">编辑</ElButton>
                        <ElButton type="danger" @click="hdlDelete(scope.row.id)">删除</ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
        </div>
    </div>
</template>

<style scoped lang="scss">
.menu-index {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
    // background-color: rgb(255, 255, 255);
    padding: 0.5rem;
}
</style>
